package com.hangsu.train.netty;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hangsu.train.components.constants.JwtConstant;
import com.hangsu.train.components.entity.User;
import com.hangsu.train.components.service.UserService;
import com.hangsu.train.netty.transfer.comsumer.ECGConsumer;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
@Component()
@Scope("prototype")
public class NioWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private UserService userService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        if(log.isDebugEnabled()){
            log.debug(" add nio channel:"+ctx.channel().id().asLongText());
            log.debug("receive message:{}",msg.text());
        }
        String message=msg.text();

        // 登录
        if (!ClientHolder.users.containsValue(ctx.channel())) {
            if(message.startsWith("login:")){
                String jwtToken=message.split(":")[1];
                if (StringUtils.isNotEmpty(jwtToken)) {
                    SignedJWT signedJWT = SignedJWT.parse(jwtToken);
                    String subject = signedJWT.getJWTClaimsSet().getSubject();

                    JWSVerifier verifier = new MACVerifier(JwtConstant.SECRET);
                    boolean verify = signedJWT.verify(verifier);
                    User user = userService.getUserByAccount(subject);
                    if (verify && user != null) {
                        ClientHolder.users.put(user.getUserCode(),ctx);
                    }
                }

            }
        }



        ECGConsumer consumer=new ECGConsumer();
        consumer.start();

        ClientHolder.getSocketClient().clear();
        ClientHolder.getSocketClient().add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        if(log.isDebugEnabled()) {
            log.debug(" remove nio channel:"+ctx.channel().id().asLongText());
        }
    }
}
